<script lang="ts" setup>
import {ref, watch} from "vue";
import {getImageThemeColor, timeout} from "@/utils/getMainColor";
import {getCategoryListApi} from "@/api/category";
import type {Category} from "@/types/category";
import {onLoad, onPullDownRefresh} from "@dcloudio/uni-app";
import Skeleton from "@/pages/category/components/Skeleton.vue";
import {ImgErrorType} from "@/enum/imgErrorType";
import {useCategoryStore} from "@/stores/category";


const {safeAreaInsets, windowHeight} = uni.getSystemInfoSync();
// 刷新
onPullDownRefresh(() => {
  networkError.value = false
  if (activeIndex.value !== -1) {
    return
  }
  // 初始化数据
  uni.$on('initCategory', () => {
    getCategoryList()
  })
  themeColorList.value = []
  getCategoryList().finally(() => uni.stopPullDownRefresh())
})
const isFinish = ref(false)
const categoryList = ref<Category[]>([])
const descLocation = ref('center')
const categoryStore = useCategoryStore();
const isImgFinish = ref<boolean[]>([]) // 是否加载完成图片
// 获取分类列表
const getCategoryList = async () => {
  const res = await getCategoryListApi()
  categoryList.value = res.data.classificationList
  categoryStore.categoryList = categoryList.value
  isFinish.value = true
  isImgFinish.value = new Array(categoryList.value.length).fill(false)
  // await getThemeColorList()
}
const activeIndex = ref(-1) // 当前选中的分类索引
const themeColorList = ref<string[]>([])
const onClickCategory = (index: number) => {
  if (activeIndex.value === index) {
    //选中情况下点击，前往分类模块
    uni.navigateTo({url: '/subPkg/categoryDetail/categoryDetail?id=' + categoryList.value[activeIndex.value].id})
  }

  // 修改当前标题
  uni.setNavigationBarTitle({
    title: categoryList.value[index].name
  })
  if (categoryList.value[index].img === ImgErrorType.ERROR_IMG_URL) {
    return
  }
  // 移动图片位置
  activeIndex.value = index
  // 设置desc位置
  if (index <= 2) {
    descLocation.value = 'center'
  } else if (index > 2 && index < 6) {
    descLocation.value = 'flex-start'
  } else {
    descLocation.value = 'center'
  }
}

// 获取主题色板集

const getThemeColorList = async () => {
  for (let index: number = 0; index < categoryList.value.length; index++) {
    try {
      const color = await Promise.race([getImageThemeColor(categoryList.value[index].img, 'categoryCanvas'), timeout()])
      themeColorList.value.push(color)
    } catch (e) {
      //await uni.showToast({title: '网络异常，请稍检查网络后,尝试刷新', icon: 'none', duration: 4000,})
      break;
    }
  }
}

onLoad(() => {
  getCategoryList()
})

//点击更多
const goMoreCategory = () => {
  if (activeIndex.value == -1) {
    return uni.navigateTo({url: '/subPkg/categoryDetail/categoryDetail'})
  }
  uni.navigateTo({url: '/subPkg/categoryDetail/categoryDetail?id=' + categoryList.value[activeIndex.value]?.id})
}
/**
 * 预加载图片
 * @param index 已完成加载的图片的索引
 */
const onLoadImg = (index: number) => {
  isImgFinish.value[index] = true
}
// 图片加载失败
const errorType = ImgErrorType
const onImgError = (index: number) => {
  categoryList.value[index].img = ImgErrorType.ERROR_IMG_URL
}

// 网络异常
const networkError = ref(false)
uni.$on('noNetwork', () => {
  if (!isFinish.value) {
    networkError.value = true
  }
  uni.showToast({title: '网络异常，请稍检查网络', icon: 'none'})
  uni.stopPullDownRefresh()
})

// 监听页面变化
watch(activeIndex, () => {
  if (activeIndex.value === -1) {
    // 当前没有一个分类被选中
    uni.setNavigationBarTitle({title: '动物分类'})
  }
})
</script>

<template>
  <aw-no-network v-if="networkError"></aw-no-network>
  <view v-else>
    <view v-if="!isFinish">
      <skeleton></skeleton>
      <aw-loader
          :styles="{position: 'absolute',top: '50%',left: '50%',transform: 'translate(-50%,-50%)'}">
      </aw-loader>
    </view>
    <view v-else :style="{'--WinHeight':windowHeight+'px'}" class="category-container" @click="activeIndex=-1">
      <view class="category-list">
        <view v-for="(item,index) in categoryList" :key="item.id" :class="{active: index === activeIndex}"
              :style="{filter:activeIndex!==-1&&activeIndex!==index?'blur(15px)':'blur(0px)'}"
              class="category-item"
              @click.stop="onClickCategory(index)">
          <view
              class="category-img active-img">
            <uv-image :mode="'aspectFill'" :src="item.img" height="100%" radius="8" width="100%">
              <template v-slot:loading>
                <uv-image mode="aspectFit" src="/static/home-selected.png" width="100%"></uv-image>
              </template>
              <template v-slot:error>
                <uv-image mode="aspectFit" src="/static/error-img.png" width="100%"></uv-image>
              </template>
            </uv-image>
          </view>
          <!--       名字遮罩   -->
          <view :style="{display:index===activeIndex?'none':'flex'}" class="flex justify-center align-center text-bold text-white"
                style="position: absolute;top: 0;left: 0;width: 100%;height: 100%;z-index: 10;background: rgba(0,0,0,.4);border-radius: 8px">
            <text class="category-name text-lg"># {{
                item.name
              }}
            </text>
          </view>
        </view>
        <view :style="{filter:activeIndex!==-1?'blur(15px)':'blur(0px)'}"
              class="category-item more-category bg-gradual-awGreen"
              @click="goMoreCategory">更多分类
          <uni-icons color="#fff" size="50" type="color-filled"></uni-icons>
          <uni-icons color="#fff" size="40" style="margin-top: 20px" type="arrow-right"></uni-icons>
        </view>
      </view>
      <uni-transition :show="activeIndex!==-1" :styles="{position:'absolute',top:'0',left:'0',bottom:'0',right:'0',background: `url(${categoryList[activeIndex]?.img})`,zIndex:activeIndex!==-1?8:-1,
            backgroundSize: 'cover',
            backgroundPosition: 'center',
            backgroundRepeat: 'no-repeat',
            filter:'blur(15px)'}"
                      mode-class="fade">
      </uni-transition>
      <uni-transition :duration="250"
                      :show="activeIndex!==-1"
                      :styles="{justifyContent:activeIndex<3||activeIndex>5?'center':'flex-end',
                  background: `linear-gradient(to bottom, ${themeColorList[activeIndex]}, #f1f1f1)`,
                  zIndex:activeIndex!==-1?9:''}" class="mask"
                      mode-class="slide-top"
                      @click="activeIndex=-1">
        <view class="category-detail">
          {{
            categoryList[activeIndex]?.desc.length > 140 ? categoryList[activeIndex]?.desc.substring(0, 120) + '...' : categoryList[activeIndex]?.desc
          }}
        </view>
        <view
            style="font-size: 20px;display: flex;justify-content: center;align-items: center;color: #ffffff;align-self: flex-end"
            @click="goMoreCategory">
          查看更多
          <text class="cuIcon-roundrightfill text-awGreen text-shadow" style="font-size: 22px"></text>
        </view>
      </uni-transition>
    </view>
  </view>
</template>

<style lang="scss">
.category-container {
  width: 100%;
  background-color: #f1f1f1;
  height: var(--WinHeight);
  /* #ifndef H5 */
  height: 100vh;
  /* #endif */
  .category-list {
    transition: all 0.2s;
    position: relative;
    display: flex;
    flex-wrap: wrap;
    width: 100%;
    height: 100%;
    /* #ifdef H5 */
    height: 90%;
    /* #endif */
    justify-content: center;

    .category-item {
      transition: all 0.4s;
      width: 30%;
      height: 30%;
      max-height: 230px;
      display: flex;
      flex-direction: column;
      align-items: center;
      margin: 10rpx 10rpx 0 10rpx;
      overflow: hidden;
      //  添加阴影
      box-shadow: 0 0 3px rgba(0, 0, 0, 0.1);
      border-radius: 8px;

      .category-img {
        width: 100%;
        height: 100%;
        border-radius: 8px;
      }

      .category-name {
        color: #fff;
      }
    }

    .more-category {
      display: flex;
      justify-content: center;
      align-items: center;
      background-color: #39c5bb;
      border-radius: 10px;
      height: 25%;
      max-height: 180px;
      color: #ffffff;
      margin: 40rpx 0 0 0;
    }
  }
}

.active-name {
  font-size: larger;
  color: #0a0a0a;
  font-weight: bold;
}

.active {
  transition: all 0.2s;
  z-index: 9999;
  transform: scale3d(1.1, 1.1, 1.2);
  display: flex;
  justify-content: center;
  align-items: center;
  color: white;
  font-size: larger;
  font-weight: bold;
}

.mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  transition: all 0.3s;
  opacity: 0.7 !important;
  padding: 30rpx 20rpx;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  z-index: -1;
  background-color: rgba(255, 255, 255, 0.3);
  backdrop-filter: blur(10px);

  .category-detail {
    color: black;
    font-size: 20px;
    text-indent: 2em;
    z-index: 9999;
    opacity: 1;
  }
}


</style>
